//
//  XNetWorkManager.swift
//  WeiBoReDo
//
//  Created by 放学跟鸽走 on 2017/4/8.
//  Copyright © 2017年 放学跟鸽走. All rights reserved.
//

import Foundation
import AFNetworking
enum XNetworkMethod {
    case GET
    case POST
}
class XNetworkManager:AFHTTPSessionManager{
    
    private let MAX_TRY_ERROR_COUNT = 3
    private var TRY_ERROR_COUNT = 0
    lazy var userAccount:XUserAccount = XUserAccount()
    var isLogin:Bool{
        return userAccount.access_token != nil
    }
    //单例
    /// 静态区／常量／闭包
    /// 在第一次访问时，执行闭包，并且将结果保存在 shared 常量中
    static let shared:XNetworkManager = {
        // 实例化对象
        let instance = XNetworkManager()
        
        // 设置响应反序列化支持的数据类型
        
        instance.responseSerializer.acceptableContentTypes?.insert("text/html")
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        // 返回对象
        return instance
    }()
    ///网络请求
    ///
    ///
    /// - Parameters:
    ///   - method: 请求方法，默认为GET
    ///   - urlString: 请求url
    ///   - params: 参数字典
   
    ///   - complete: 返回json字典与成功标识
    func request(method: XNetworkMethod = .GET,urlString:String,params:[String:Any]?,complete:@escaping ((_ json:Any?,_ isSuccess:Bool)->())){
        let successBlock = {(task:URLSessionDataTask?, json:Any?) in
            complete(json,true)
        }
        let failureBlock = {(task:URLSessionDataTask?, error:Error) in
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                print("Token 过期了")
                if self.TRY_ERROR_COUNT > self.MAX_TRY_ERROR_COUNT{
                    
                }else{
                    self.TRY_ERROR_COUNT += 1
                    // 发送通知，提示用户再次登录(本方法不知道被谁调用，谁接收到通知，谁处理！)
                    NotificationCenter.default.post(
                        name: NSNotification.Name(rawValue: XUserShouldLoginNotification),
                        object: "bad token")
                }
            }
            
            print("网络请求错误 \(error)")
            complete(nil,false)
        }
        
        if method == .GET {
            get(urlString, parameters: params, progress: nil, success:successBlock, failure: failureBlock)
        }else{
            post(urlString, parameters: params, progress: nil, success: successBlock, failure: failureBlock)
        }
    }
    /// 自带token的请求
    ///
    /// - Parameters:
    ///   - method: 请求方法，默认为GET
    ///   - urlString: 请求url
    ///   - params: 参数字典
    ///   - complete: 返回json字典与成功标识
    func tokenRequest(method: XNetworkMethod = .GET,urlString:String,params:[String:Any]?,complete:@escaping ((_ json:Any?,_ isSuccess:Bool)->())){
        //判断有没有token
        guard let token = userAccount.access_token
            else{
            NotificationCenter.default.post(name: NSNotification.Name.init(XUserShouldLoginNotification), object: nil)
                complete(nil,false)
                return
        }
        //在params中添加token
        var parameters = params
        if parameters == nil{
            parameters = [String:Any]()
        }
        parameters?["access_token"] = token
        request(method: method, urlString: urlString, params: parameters, complete: complete)
    
    }
    
    
}
